package top.haijunit.work.core.doamin;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * Validation参数验证
 *
 * @author zhanghaijun
 * @since 2024-09-18
 */
public class ValidChecks {

    /**
     * 校验分组新增参数
     */
    public interface GroupAdd {
    }

    /**
     * 校验分组编辑参数
     */
    public interface GroupEdit {
    }

    private static final ValidatorFactory validatorFactory = Validation.byDefaultProvider().configure().messageInterpolator(new ParameterMessageInterpolator()).buildValidatorFactory();

    private static <T> Map<String, String> validate(T t, Class<?>... groups) {
        Validator validator = validatorFactory.getValidator();
        Set<ConstraintViolation<T>> validate = validator.validate(t, groups);
        if (validate.isEmpty()) {
            return Collections.emptyMap();
        } else {
            LinkedHashMap<String, String> errors = new LinkedHashMap<>();
            for (ConstraintViolation<T> violation : validate) {
                errors.put(violation.getPropertyPath().toString(), violation.getMessage());
            }
            return errors;
        }
    }

    public static <T> Result<Map<String, String>> validateResult(T t, Class<?>... groups) {
        Map<String, String> validate = validate(t, groups);
        if (validate.isEmpty()) {
            return Result.success(validate);
        }
        return Result.of(ExceptionEnum.BODY_NOT_MATCH, validate);
    }
}
